<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="报表类型">
              <el-select v-model="searchForm.reportType" placeholder="请选择报表类型" @change="handleReportTypeChange"
                style="width: 100%">
                <el-option v-for="item in reportTypeOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="水厂选择">
              <el-select v-model="searchForm.factoryIds" placeholder="请选择水厂" :multiple="isMultiFactory" collapse-tags
                collapse-tags-tooltip style="width: 100%">
                <el-option v-for="item in factoryOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="开始日期">
              <el-date-picker v-model="searchForm.beginDate" type="date" placeholder="选择开始日期" value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="结束日期">
              <el-date-picker v-model="searchForm.endDate" type="date" placeholder="选择结束日期" value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <div class="form-actions">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
              <el-button type="success" @click="handleExport">导出Excel</el-button>
            </div>
          </el-col>
        </el-row>

      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="table-card">
      <el-table :data="tableData" v-loading="loading" border stripe style="width: 100%">
        <el-table-column v-for="column in tableColumns" :key="column.field" :prop="column.field" :label="column.title"
          :align="getColumnAlign(column.field)" :min-width="getColumnWidth(column.field)" show-overflow-tooltip>
          <template #default="{ row }">
            <span :class="getCellClass(row, column.field)">
              {{ formatCellValue(row[column.field], column.field) }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance()

// API引入
import {
  getReportTypes,
  getFactoryList,
  getReportColumns,
  queryProductionReport
} from '@/api/dispatch/analyze/water_plant_production'

// 搜索表单
const searchForm = reactive({
  reportType: '',
  factoryIds: [],
  beginDate: dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
  endDate: dayjs().format('YYYY-MM-DD')
})

// 下拉选项
const reportTypeOptions = ref([])
const factoryOptions = ref([])

// 表格数据
const tableData = ref([])
const tableColumns = ref([])
const loading = ref(false)

// 初始化数据
onMounted(() => {
  initData()
})

// 初始化数据
const initData = async () => {
  try {
    await Promise.all([
      fetchReportTypes(),
      fetchFactoryList()
    ])

    // 设置默认报表类型
    if (reportTypeOptions.value.length > 0) {
      searchForm.reportType = reportTypeOptions.value[0].value
      await fetchReportColumns()
    }

    // 设置默认水厂
    if (factoryOptions.value.length > 0) {
      searchForm.factoryIds = [factoryOptions.value[0].dictValue]
    }

    // 查询数据
    await fetchReportData()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  }
}

// 获取报表类型列表
const fetchReportTypes = async () => {
  try {
    const res = await getReportTypes()
    reportTypeOptions.value = res.data || []
  } catch (error) {
    console.error('获取报表类型失败:', error)
    ElMessage.error('获取报表类型失败')
  }
}

// 获取水厂列表
const fetchFactoryList = async () => {
  try {
    const res = await getFactoryList()
    factoryOptions.value = res.data || []
  } catch (error) {
    console.error('获取水厂列表失败:', error)
    ElMessage.error('获取水厂列表失败')
  }
}

// 获取报表列定义
const fetchReportColumns = async () => {
  try {
    const res = await getReportColumns({
      reportType: searchForm.reportType
    })
    tableColumns.value = res.data || []
  } catch (error) {
    console.error('获取列定义失败:', error)
    ElMessage.error('获取列定义失败')
  }
}

// 查询报表数据
const fetchReportData = async () => {
  try {
    loading.value = true

    const params = {
      reportType: searchForm.reportType,
      factoryIds: searchForm.factoryIds,
      beginDate: searchForm.beginDate,
      endDate: searchForm.endDate
    }

    const res = await queryProductionReport(params)
    tableData.value = res.data?.rows || []

    ElMessage.success(`查询成功，共 ${tableData.value.length} 条记录`)
  } catch (error) {
    console.error('查询报表数据失败:', error)
    ElMessage.error('查询报表数据失败')
  } finally {
    loading.value = false
  }
}

// 处理报表类型变化
const handleReportTypeChange = async () => {
  await fetchReportColumns()
  await fetchReportData()
}

// 处理查询
const handleSearch = () => {
  fetchReportData()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    reportType: reportTypeOptions.value[0]?.value || '',
    factoryIds: factoryOptions.value.length > 0 ? [factoryOptions.value[0].dictValue] : [],
    beginDate: dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
    endDate: dayjs().format('YYYY-MM-DD')
  })
  handleSearch()
}

// 导出Excel
const handleExport = async () => {
  try {
    if (tableData.value.length === 0) {
      ElMessage.warning('没有数据可导出')
      return
    }

    const params = {
      reportType: searchForm.reportType,
      factoryIds: searchForm.factoryIds,
      beginDate: searchForm.beginDate,
      endDate: searchForm.endDate
    }

    const fileName = `${currentReportTypeLabel}_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`

    // 使用proxy.download进行导出
    proxy.download('/dispatch/prod/report/export', params, fileName)
    ElMessage.success('导出任务已开始')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 刷新数据
const refreshData = () => {
  fetchReportData()
}

// 计算属性
const currentReportTypeLabel = computed(() => {
  const type = reportTypeOptions.value.find(item => item.value === searchForm.reportType)
  return type?.label || '生产报表'
})

const isMultiFactory = computed(() => {
  return searchForm.reportType === 'MULTI' || searchForm.reportType === 'SUMMARY'
})

// 工具函数
const getColumnAlign = (field) => {
  if (field.includes('rate') || field.includes('ratio') || field.includes('percent')) {
    return 'center'
  }
  if (field.includes('amount') || field.includes('quantity') || field.includes('count')) {
    return 'right'
  }
  return 'left'
}

const getColumnWidth = (field) => {
  const column = tableColumns.value.find(col => col.field === field)
  const titleLength = column?.title?.length || 0
  return Math.max(100, titleLength * 15 + 20)
}

const getCellClass = (row, field) => {
  const value = row[field]

  if (typeof value === 'number') {
    if (field.includes('rate') || field.includes('ratio')) {
      if (value >= 0.9) return 'cell-high'
      if (value >= 0.8) return 'cell-medium'
      if (value < 0.8) return 'cell-low'
    }

    if (field.includes('efficiency')) {
      if (value >= 0.95) return 'cell-high'
      if (value >= 0.85) return 'cell-medium'
      if (value < 0.85) return 'cell-low'
    }
  }

  return ''
}

const formatCellValue = (value, field) => {
  if (value == null) return '-'

  if (typeof value === 'number') {
    if (field.includes('rate') || field.includes('ratio') || field.includes('percent')) {
      return (value * 100).toFixed(2) + '%'
    }
    if (field.includes('amount') || field.includes('money')) {
      return '¥' + value.toLocaleString()
    }
    if (Number.isInteger(value)) {
      return value.toLocaleString()
    }
    return value.toFixed(2)
  }

  if (typeof value === 'string' && value.includes('T')) {
    try {
      return dayjs(value).format('YYYY-MM-DD HH:mm')
    } catch {
      return value
    }
  }

  return value
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.search-card {
}

.form-actions {
  text-align: center;
}

.table-card {
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.data-count {
  color: #666;
  font-size: 14px;
}

// 单元格样式
.cell-high {
  color: #67c23a;
  font-weight: bold;
}

.cell-medium {
  color: #e6a23c;
  font-weight: bold;
}

.cell-low {
  color: #f56c6c;
  font-weight: bold;
}

:deep(.el-table) {
  .cell {
    white-space: nowrap;
  }
}

:deep(.el-table__header) {
  th {
    background-color: #f5f7fa;
    font-weight: bold;
  }
}

:deep(.el-card) {
  margin-bottom: 20px;
}

:deep(.el-card):last-child {
  margin-bottom: 0;
}

@media (max-width: 768px) {
  .search-form .el-col {
    margin-bottom: 15px;
  }

  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .table-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}

.search-card :deep(.el-form-item) {
    margin-bottom: 0px !important;
}
</style>